package cn.sofwin.blog.servlet;

import cn.sofwin.blog.entity.Article;
import cn.sofwin.blog.entity.User;
import cn.sofwin.blog.service.ArticleService;
import cn.sofwin.blog.service.impl.ArticleServiceImpl;
import cn.sofwin.blog.utils.HttpHelper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 控制器
 * @author LetCode
 * @since 1.0
 *
 */
@WebServlet("/blog/article/edit")
public class ArticleEditServlet extends HttpServlet {

    private ArticleService articleService = ArticleServiceImpl.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");

        if (StringUtils.isNoneBlank(id)){
            Article article=articleService.getArticleById(Integer.parseInt(id));
            req.setAttribute("a",article);
        }

        req.getRequestDispatcher("/edit.jsp").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpHelper.charset(req);
        String id=req.getParameter("id");
        String title = req.getParameter("title");
        String summary = req.getParameter("summary");
        String content = req.getParameter("content");
        User user= (User) req.getSession().getAttribute("LOGIN_USER");
        if (StringUtils.isBlank(id)){
            articleService.writeArticle(user,title,summary,content);
        }else {
            articleService.edit(id,summary,content);
        }
        resp.sendRedirect("/index");
    }


}